package net.pingfang.util;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * @Author: CM
 * @Date: 2021/6/3 14:37
 * @Description: 反射工具类
 */
@Slf4j
public class ReflectUtil {

    /**
     * 根据字段名称反射设置值
     *
     * @param object    目标对象
     * @param fieldName 字段名称
     * @param value     目标值
     */
    public static void setFieldValueByName(Object object, String fieldName, String value) {
        if (object == null || StringUtils.isEmpty(fieldName)) {
            return;
        }
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(object, value);
        } catch (Exception exc) {
            try {
                Field field = object.getClass().getField(fieldName);
                field.setAccessible(true);
                field.set(object, value);
            } catch (Exception exception) {
                log.error(ExceptionUtil.getStackTrace(exception));
            }
        }
    }


    /**
     * 反射获取某对象字段值
     * @param object
     * @param targetFieldName
     * @return
     * @throws Exception
     */
    public static Object getFieldValueByObject(Object object, String targetFieldName){

        // 获取该对象的Class
        Class objClass = object.getClass();
        // 初始化返回值
        Object result = null;
        // 获取所有的属性数组
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            // 属性名称
            String currentFieldName = "";
            // 获取属性上面的注解 import com.fasterxml.jackson.annotation.JsonProperty;
            /**
             * 举例： @JsonProperty("roleIds")
             * private String roleIds;
             */
            try {
                boolean has_JsonProperty = field.isAnnotationPresent(JsonProperty.class);

                if (has_JsonProperty) {
                    currentFieldName = field.getAnnotation(JsonProperty.class).value();
                } else {
                    currentFieldName = field.getName();
                }

                if (currentFieldName.equals(targetFieldName)) {
                    field.setAccessible(true);
                    result = field.get(object);

                    return result; // 通过反射拿到该属性在此对象中的值(也可能是个对象)
                }
            } catch (SecurityException | IllegalAccessException | IllegalArgumentException e) {
                log.error(ExceptionUtil.getStackTrace(e));
            }

        }

        return result;
    }
}
